<template>
  <div class="settle-manage">
    <!--     <div v-if="!enterpriseId" class="empty-state">
      <p>请选择左侧企业查看对应的结算单汇总信息</p>
    </div>

    <div v-else> -->
    <div>
      <!-- 搜索筛选 -->
      <el-form :inline="true" :model="headerForm">
        <el-form-item label="所属商户" class="form-item-wrapper">
          <el-select v-model="headerForm.tenantId" placeholder="请选择所属商户" clearable style="width: 180px"
            @change="loadLocationData" filterable remote :remote-method="searchMerchant">
            <el-option v-for="item in merchantList" :key="item.id" :label="item.tenantName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="所在地点位置" class="form-item-wrapper">
          <el-tree-select v-model="headerForm.locationIds" :data="fullLocationTree" multiple collapse-tags
            collapse-tags-tooltip :render-after-expand="false" show-checkbox :filter-node-method="filterNodeMethod"
            filterable node-key="id" value-key="id" :props="locationTreeProps" @check="loadEnterpriseData"
            placeholder="请选择所在地点位置" clearable style="width: 180px" />
        </el-form-item>
        <el-form-item label="企业简称" class="form-item-wrapper">
          <el-select v-model="headerForm.enterpriseIds" multiple collapse-tags collapse-tags-tooltip clearable
            placeholder="请选择企业简称" style="width: 185px" filterable remote :remote-method="searchEnterprise">
            <el-option v-for="item in enterpriseList" :key="item.id" :label="item.shortName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="账期" class="form-item-wrapper">
          <el-input v-model="headerForm.billPeriod" placeholder="请输入账期，如：2024-01" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="开始日期" class="form-item-wrapper">
          <el-date-picker v-model="headerForm.startDate" type="date" clearable format="YYYY-MM-DD"
            value-format="YYYY-MM-DD" placeholder="选择开始日期" style="width: 130px" />
        </el-form-item>
        <el-form-item label="结束日期" class="form-item-wrapper">
          <el-date-picker v-model="headerForm.endDate" type="date" clearable format="YYYY-MM-DD"
            value-format="YYYY-MM-DD" placeholder="选择结束日期" style="width: 130px" />
        </el-form-item>
        <el-form-item label="付款状态" class="form-item-wrapper">
          <el-select v-model="headerForm.paymentStatus" placeholder="全部" style="width: 100px">
            <el-option label="全部" value="" />
            <el-option label="待付款" :value="0" />
            <el-option label="已付款" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="确认状态" class="form-item-wrapper">
          <el-select v-model="headerForm.confirmStatus" placeholder="全部" style="width: 100px">
            <el-option label="全部" value="" />
            <el-option label="待确认" :value="0" />
            <el-option label="已确认" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            查询
          </el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <div style="margin-bottom: 15px;">
        <el-button type="primary" @click="handleNewSettle" v-if="settlePermissions">
          选择账期结算
        </el-button>
        <el-button type="success" :disabled="tableData.list.length === 0" @click="handleExportAll">
          全部导出
        </el-button>
        <el-button type="danger" :disabled="selectedRows.length === 0" @click="handleBatchSettle" v-if="settlePermissions">
          重新结算
        </el-button>
        <el-button type="primary" :disabled="selectedRows.length === 0" @click="handleBatchConfirm" v-if="settlePermissions">
          批量确认
        </el-button>
        <span style="margin-left: 10px; color: #909399; font-size: 14px;">
          已选择 {{ selectedRows.length }} 条
        </span>
      </div>

      <!-- 结算单列表 -->
      <el-table ref="tableRef" :data="tableData.list" highlight-current-row stripe row-key="id" style="width: 100%"
        @selection-change="handleSelectionChange" v-loading="loading" class="scroll-box" :max-height="tableMaxHeight">
        <el-table-column type="selection" header-align="center" width="40" :selectable="isSelectable" />
        <el-table-column prop="shortName" header-align="center" label="企业简称" />
        <el-table-column prop="billPeriod" header-align="center" label="账期" />
        <el-table-column prop="startDate" header-align="center" align="center" label="开始日期" />
        <el-table-column prop="endDate" header-align="center" align="center" label="结束日期" />
        <el-table-column label="总费用金额">
          <template #default="{ row }">
            {{ row.totalFeeAmount }}元
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="center" label="付款状态">
          <template #default="{ row }">
            <el-tag :type="row.paymentStatus === 1 ? 'success' : 'warning'" size="small">
              {{ row.paymentStatus === 1 ? '已付款' : '待付款' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="center" label="付款日期">
          <template #default="{ row }">
            {{ row.paymentDate || '-' }}
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="center" label="确认状态">
          <template #default="{ row }">
            <el-tag :type="row.confirmStatus === 1 ? 'success' : 'warning'" size="small">
              {{ row.confirmStatus === 1 ? '已确认' : '待确认' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="确认时间" header-align="center" align="center" min-width="100">
          <template #default="{ row }">
            {{ row.confirmTime || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" header-align="center" min-width="140">
          <template #default="{ row }">
            <div class="flex-wrapper">
              <el-button type="primary" link @click="viewDetail(row)">
                查看
              </el-button>
              <el-button v-if="settlePermissions && row.paymentStatus === 0" type="warning" link @click="handlePayment(row)">
                付款
              </el-button>
              <el-button v-if="settlePermissions && row.confirmStatus === 0" type="success" link @click="handleConfirm(row)">
                确认
              </el-button>
              <el-dropdown class="btn-dropdown">
                <el-button link type="primary">更多<el-icon class="el-icon--right">
                    <ArrowDown />
                  </el-icon></el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handleShare(row)">分享</el-dropdown-item>
                    <el-dropdown-item v-if="canEdit(row)" @click="handleEdit(row)">编辑</el-dropdown-item>
                    <el-dropdown-item v-if="canEdit(row)" @click="handleEditDetail(row)">编辑明细</el-dropdown-item>
                    <el-dropdown-item v-if="canEdit(row)" @click="handleSettle(row)">重新结算</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <Pagination :pageProps="pageProps" layout="prev, pager, next" @search="getList" style="margin-top: 10px;" />

      <!-- 详情弹窗 -->
      <el-dialog v-model="detailDialogVisible" title="结算单详情" width="80%" :close-on-click-modal="false" align-center>
        <div v-loading="detailLoading" class="detail-content">
          <div v-if="currentDetail">
            <!-- 基本信息 -->
            <div class="detail-section">
              <h3>基本信息</h3>
              <el-descriptions :column="2" border>
                <el-descriptions-item label="结算单汇总ID">
                  {{ currentDetail.id }}
                  <el-button type="success" @click="handleCopyId" style="margin-left: 20px;">
                    复制
                  </el-button>
                </el-descriptions-item>
                <el-descriptions-item label="当前账期">
                  {{ currentDetail.billPeriod || '-' }}
                </el-descriptions-item>
                <el-descriptions-item label="企业名称">
                  {{ currentDetail.enterpriseName || '-' }}
                </el-descriptions-item>
                <el-descriptions-item label="企业地址">
                  {{ currentDetail.companyAddress || '-' }}
                </el-descriptions-item>
                <el-descriptions-item label="开始日期-结束日期">
                  {{ currentDetail.startDate }} / {{ currentDetail.endDate }}
                </el-descriptions-item>
                <el-descriptions-item label="总费用金额">
                  {{ currentDetail.totalFeeAmount }}元
                </el-descriptions-item>
                <el-descriptions-item label="付款状态">
                  <el-tag :type="currentDetail.paymentStatus === 1 ? 'success' : 'warning'" size="small">
                    {{ currentDetail.paymentStatus === 1 ? '已付款' : '待付款' }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="商户简称">
                  {{ currentDetail.tenantName || '-' }}
                </el-descriptions-item>
                <el-descriptions-item label="付款日期">
                  {{ currentDetail.paymentDate || '-' }}
                </el-descriptions-item>
              </el-descriptions>
            </div>

            <!-- 明细列表 -->
            <div class="detail-section">
              <h3>费用明细</h3>
              <el-table :data="detailList" stripe style="width: 100%">
                <el-table-column prop="groupName" label="明细名称" />
                <el-table-column prop="objectType" label="对象类型" />
                <el-table-column prop="billPeriod" label="账期" />
                <el-table-column prop="startDate" label="开始日期" />
                <el-table-column prop="endDate" label="结束日期" />
                <el-table-column prop="currentUsage" label="实际用量">
                  <template #default="{ row }">
                    {{ row.currentUsage }}{{ getUsageUnit(row.objectType) }}
                  </template>
                </el-table-column>
                <el-table-column prop="unitPrice" label="计费单价">
                  <template #default="{ row }">
                    {{ row.unitPrice }}元
                  </template>
                </el-table-column>
                <el-table-column prop="feeAmount" label="费用金额">
                  <template #default="{ row }">
                    {{ row.feeAmount }}元
                  </template>
                </el-table-column>
                <el-table-column prop="allocationRatio" label="分摊比例">
                  <template #default="{ row }">
                    {{ row.allocationRatio }}%
                  </template>
                </el-table-column>
                <el-table-column prop="createMethod" label="创建方式">
                  <template #default="{ row }">
                    {{ row.createMethod == 0 ? '系统创建' : '人工创建' }}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>

        <template #footer>
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </template>
      </el-dialog>

      <!-- 编辑结算单明细弹窗 -->
      <el-dialog v-model="editDetailDialogVisible" title="编辑结算单明细" width="80%" :close-on-click-modal="false" align-center>
        <div v-loading="editDetailLoading" class="detail-content">
          <div v-if="detailList.length > 0">
            <!-- 明细列表 -->
            <div class="detail-section">
              <div style="margin-bottom: 20px;">
                  <el-button type="primary" @click="handleAddSettleBillDetail('房租')">添加房租明细</el-button>
                  <el-button type="primary" @click="handleAddSettleBillDetail('电表')">添加电表明细</el-button>
                  <el-button type="primary" @click="handleAddSettleBillDetail('水表')">添加水表明细</el-button>
              </div>
              <el-table :data="detailList" stripe style="width: 100%">
                <el-table-column prop="groupName" label="明细名称" />
                <el-table-column prop="objectType" label="对象类型" />
                <el-table-column prop="billPeriod" label="账期" />
                <el-table-column prop="startDate" label="开始日期" />
                <el-table-column prop="endDate" label="结束日期" />
                <el-table-column prop="currentUsage" label="当期用量">
                  <template #default="{ row }">
                    {{ row.currentUsage }}{{ getUsageUnit(row.objectType) }}
                  </template>
                </el-table-column>
                <el-table-column prop="unitPrice" label="计费单价">
                  <template #default="{ row }">
                    {{ row.unitPrice }}元
                  </template>
                </el-table-column>
                <el-table-column prop="feeAmount" label="费用金额">
                  <template #default="{ row }">
                    {{ row.feeAmount }}元
                  </template>
                </el-table-column>
                <el-table-column prop="allocationRatio" label="分摊比例">
                  <template #default="{ row }">
                    {{ row.allocationRatio }}%
                  </template>
                </el-table-column>
                <el-table-column prop="createMethod" label="创建方式">
                  <template #default="{ row }">
                    {{ row.createMethod == 0 ? '系统创建' : '人工创建' }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" header-align="center" align="center" min-width="60">
                  <template #default="{ row }">
                    <el-button v-if="row.confirmStatus === 0" type="primary" link @click="handleEditSettleBillDetail(row)">
                      编辑
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>

        <template #footer>
          <el-button @click="handleCloseEditDetailDialog">关闭</el-button>
        </template>

        <SettleBillDetailDialog ref="settleBillDetailDialogRef" @reload="doGetSettleBillTotalDetail" />
      </el-dialog>

      <!-- 结算企业结算单弹窗 -->
      <EnterpriseListDialog ref="enterpriseListDialogRef" @reload="getList" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted,computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from 'vue-router';
import type { EnterpriseTreeNode } from '@/api/types/enterprise';
import Pagination from "@/components/Pagination/Index.vue";
import { 
  getSettleBillTotalList, getSettleBillTotalDetail, updateSettleBillTotalPaid, 
  updateSettleBillTotal, confirmSettleBillTotal, getMerchantByName,
  getLocationTree, getEnterpriseList, resettleBillTotal, 
  exportSettleBillTotal, updateSettleBillDetail, getSettlePermissions } from '@/api/settle';
import { isPositiveFloat } from "@/utils/validate";
import { LocationTreeNode } from '@/api/types/location'
import { copyValue, getUsageUnit } from '@/utils/index';
import SettleBillDetailDialog from './SettleBillDetailDialog.vue'
import EnterpriseListDialog from './EnterpriseListDialog.vue'

const router = useRouter();

const loading = ref(false)
const enterpriseId = ref(0);
const tableRef = ref();
const selectedRows = ref<any[]>([]);
const tableMaxHeight = ref(0);

const headerForm = reactive({
  tenantId: null,
  locationIds: [],
  enterpriseIds: [],
  billPeriod: "",
  startDate: "",
  endDate: "",
  paymentStatus: "",
  confirmStatus: "",
});

const pageProps = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});

const tableData = reactive({
  list: [] as any,
});

// 详情弹窗相关
const detailDialogVisible = ref(false);
const currentDetail = ref<any>(null);
const detailList = ref<any[]>([]);
const detailLoading = ref(false);

// 编辑结算单明细弹窗相关
const editDetailDialogVisible = ref(false);
const editDetailLoading = ref(false);
const settleBillTotalId = ref(0);
const settleBillDetailDialogRef = ref()
// 结算操作权限
const settlePermissions = ref(false);

const handleEditDetail = async (row: any) => {
  if (!validateBillId(row)) return;
  settleBillTotalId.value = row.id
  doGetSettleBillTotalDetail()
};

const doGetSettleBillTotalDetail = async () => {
  editDetailLoading.value = true;
  detailList.value = [];

  try {
    const response = await getSettleBillTotalDetail(settleBillTotalId.value);
    if (response.success) {
      const data = response.data;
      currentDetail.value = data;
      detailList.value = data.detailList || [];
      editDetailDialogVisible.value = true;
    } else {
      handleApiError(response, '获取详情失败');
    }
  } catch (error) {
    ElMessage.error('获取详情失败，请稍后重试');
  } finally {
    editDetailLoading.value = false;
  }
}

const handleAddSettleBillDetail = (objectType: '水表' | '电表' | '房租') => {
  if (!settleBillDetailDialogRef.value) return;
  const settleBillDetail = {
    objectType: objectType
  }
  settleBillDetailDialogRef.value.openDialog('create', currentDetail.value, settleBillDetail);
}

const handleEditSettleBillDetail = (row: any) => {
  if (row.createMethod == 1) {
    // 人工创建的结算单明细
    if (settleBillDetailDialogRef.value) {
      const settleBillDetail = {
        id: row.id,
        detailName: row.groupName,
        objectType: row.objectType,
        currentUsage: row.currentUsage,
        unitPrice: row.unitPrice,
      }
      settleBillDetailDialogRef.value.openDialog('edit', currentDetail.value, settleBillDetail)
    }
  } else {
    // 系统创建的结算单明细，只能修改当期用量
    ElMessageBox.prompt(`请修改当期用量，单位：${getUsageUnit(row.objectType)}`, `编辑当期用量`, {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValue: row.currentUsage,
      inputPattern: /\S+/, inputErrorMessage: '当期用量不能为空'
    }).then(({ value }) => {
      if (!isPositiveFloat(value)) {
        ElMessage.error('当期用量必须是数字');
        return;
      }
      let requestData = {
        id: row.id,
        currentUsage: value
      }
      updateSettleBillDetail(requestData)
        .then((res: any) => {
          ElMessage.success("修改成功！");
          doGetSettleBillTotalDetail();
        })
        .catch((err: any) => {
          console.error("err", err.msg);
          ElMessage.error("修改失败！");
        });
    });
  }
}

const handleCloseEditDetailDialog = () => {
  editDetailDialogVisible.value = false;
  getList()
}

const updateData = (enterprise: EnterpriseTreeNode) => {
  enterpriseId.value = enterprise.id;
  getList();
};

// 商户列表
const merchantList = ref<any[]>([]);

// 获取商户列表
const getMerchantList = (name?: string) => {  
  // 使用新的按名称查询接口
  getMerchantByName(name).then((res: any) => {
    if (res.success && res.data) {
      merchantList.value = Array.isArray(res.data) ? res.data : []
    } else {
      console.warn('未获得到商户列表:', res)
      merchantList.value = []
    }
  }).catch((err: any) => {
    console.error('获取商户列表失败', err)    
  })
};

const searchMerchant = (name: string) => {
  getMerchantList(name)
}

// 地点位置数据
const fullLocationTree = ref<LocationTreeNode[]>([])
const locationTreeProps = ref({
  label: 'name'
});

// 加载地点位置数据
const loadLocationData = async () => {
  try {
    if (!headerForm.tenantId) {
      fullLocationTree.value = []
      return
    }
    enterpriseList.value = []
    loadEnterpriseData()
    
    const res = await getLocationTree(headerForm.tenantId)
    if (res.success && res.data) {
      fullLocationTree.value = res.data
    } else {
      const errorMsg = res.msg || '加载地点位置数据失败'
      ElMessage.error(`加载失败: ${errorMsg}`)
      fullLocationTree.value = []
    }
  } catch (error) {
    ElMessage.error('网络请求失败，请检查网络连接后重试')
    fullLocationTree.value = []
  }
}

const filterNodeMethod = (value: string, data: any) => {
  return value ? data.name.includes(value) : true;
}

// 企业列表
const enterpriseList = ref<any[]>([]);

// 加载企业数据
const loadEnterpriseData = async () => {
  let requestData = {
    tenantId: headerForm.tenantId,
    locationIds: headerForm.locationIds,
  }
  doGetEnterpriseList(requestData)
}

// 搜索企业数据
const searchEnterprise = async (shortName: string) => {
  let requestData = {
    shortName: shortName,
    tenantId: headerForm.tenantId,
    locationIds: headerForm.locationIds,
  }
  doGetEnterpriseList(requestData)
}

const doGetEnterpriseList = (requestData: any) => {
  getEnterpriseList(requestData).then((res: any) => {
    if (res.success && res.data) {
      enterpriseList.value = Array.isArray(res.data) ? res.data : []
    } else {
      enterpriseList.value = []
    }
  }).catch((err: any) => {
    console.error('获取企业列表失败', err)
  })
}

const getList = () => {
//  if (!enterpriseId.value) return;
  loading.value = true
  getSettleBillTotalList({
      enterpriseIds: headerForm.enterpriseIds,
      locationIds: headerForm.locationIds,
      tenantId: headerForm.tenantId,
      billPeriod: headerForm.billPeriod || undefined,
      startTime: headerForm.startDate || undefined,
      endTime: headerForm.endDate || undefined,
      paymentStatus: headerForm.paymentStatus,
      confirmStatus: headerForm.confirmStatus,
      pageNum: pageProps.value.pageNum,
      pageSize: pageProps.value.pageSize
    }).then((response) => {
      loading.value = false
      if (response.success) {
        const data = response.data;
        tableData.list = data.records || [];
        pageProps.value.total = data.total || 0;
      } else {
        handleApiError(response, '获取数据失败');
        tableData.list = [];
        pageProps.value.total = 0;
      }
    }).catch((err: any) => {
      loading.value = false
      console.error("err", err.msg);
      ElMessage.error("获取数据失败");
    });
};

const handleSearch = () => {
  pageProps.value.pageNum = 1;
  getList();
};

const resetFilter = () => {
  Object.assign(headerForm, {
    tenantId: null,
    locationIds: [],
    enterpriseIds: [],
    billPeriod: "",
    startDate: "",
    endDate: "",
    paymentStatus: "",
    confirmStatus: "",
  });
  Object.assign(pageProps.value, {
    pageNum: 1,
    pageSize: 10,
    total: 0,
  });
  getList();
};

// 验证结算单ID
const validateBillId = (row: any): boolean => {
  if (!row.id) {
    ElMessage.error('结算单ID不存在');
    return false;
  }
  return true;
};

const viewDetail = async (row: any) => {
  if (!validateBillId(row)) return;
  
  detailLoading.value = true;
  currentDetail.value = null;
  detailList.value = [];
  
  try {
    const response = await getSettleBillTotalDetail(row.id);
    
    if (response.success) {
      const data = response.data;
      currentDetail.value = data;
      detailList.value = data.detailList || [];
      detailDialogVisible.value = true;
    } else {
      handleApiError(response, '获取详情失败');
    }
  } catch (error) {
    ElMessage.error('获取详情失败，请稍后重试');
  } finally {
    detailLoading.value = false;
  }
};

// 获取用量单位
// 处理API响应错误
const handleApiError = (response: any, defaultMessage: string = '操作失败') => {
  const { success, code, message, msg } = response.data || {};
  
  if (success) {
    return null; // 成功，无错误
  }
  
  // 根据code字段处理不同的错误状态
  switch (code) {
    case 401:
      ElMessage.error('未授权，请重新登录');
      // 可以在这里添加跳转到登录页的逻辑
      break;
    case 403:
      ElMessage.error('权限不足，无法访问此资源');
      break;
    case 404:
      ElMessage.error('请求的资源不存在');
      break;
    default:
      ElMessage.error(message || msg || defaultMessage);
  }
  
  return true; // 表示有错误
};

const handlePayment = async (row: any) => {
  if (!validateBillId(row)) return;
  
  try {
    await ElMessageBox.confirm(
      `确认该账单已付款？\n账期：${row.billPeriod}\n总费用金额：${row.totalFeeAmount}元`,
      '确认付款',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    const response = await updateSettleBillTotalPaid(row.id);
    
    if (response.success && response.data) {
      ElMessage.success(`付款成功`);
      getList();
    } else {
      handleApiError(response, '付款失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('付款失败，请稍后重试');
    }
  }
};

// 复选框选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
};

//按钮条件
const canEdit = (row: any) => settlePermissions.value && row.confirmStatus === 0 && row.paymentStatus === 0


// 编辑
const handleEdit = (row: any) => {
  ElMessageBox.prompt(`请修改总费用金额，单位：元`, `编辑总费用金额`, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValue: row.totalFeeAmount,
    inputPattern: /\S+/, inputErrorMessage: '总费用金额不能为空'
  }).then(({ value }) => {
    if (!isPositiveFloat(value)) {
      ElMessage.error('总费用金额必须是数字');
      return;
    }
    let requestData = {
      id: row.id,
      totalFeeAmount: value
    }
    updateSettleBillTotal(requestData)
      .then((res: any) => {
        ElMessage.success("修改成功！");
        getList();
      })
      .catch((err: any) => {
        console.error("err", err.msg);
        ElMessage.error("修改失败！");
      });
  });
};

// 确认
const handleConfirm = async (row: any) => {
  if (!validateBillId(row)) return;
  ElMessageBox.confirm(
    `确认该结算单？\n账期：${row.billPeriod}\n金额：${row.totalFeeAmount}元`,
    '确认结算单',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      let requestData = {
        idList: [row.id],
      }
      confirmSettleBillTotal(requestData)
        .then((res: any) => {
          ElMessage.success("确认成功！");
          getList();
        })
        .catch((err: any) => {
          console.error("err", err.msg);
          ElMessage.error("确认失败！");
        });
    })
    .catch((err: any) => {
      console.error("确认结算单失败:", err);
    });
};

// 批量确认
const handleBatchConfirm = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录');
    return;
  }

  ElMessageBox.confirm(
    `确认选中的 ${selectedRows.value.length} 条结算单？`,
    '批量确认结算单',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      let idList = selectedRows.value.map((item: any) => item.id);
      let requestData = {
        idList: idList,
      }
      confirmSettleBillTotal(requestData)
        .then((res: any) => {
          ElMessage.success("批量确认成功！");
          getList();
        })
        .catch((err: any) => {
          console.error("err", err.msg);
          ElMessage.error("批量确认失败！");
        });
    })
    .catch((err: any) => {
      console.error("批量确认结算单失败:", err);
    });
};

// 控制哪些行可以选择
const isSelectable = (row: any, index: number) => {
  return row.confirmStatus === 0 && row.paymentStatus === 0
}

// 导出功能
const handleShare = (row: any) => {
  if (!validateBillId(row)) return;
  
  // 生成 Export 页面的 URL
  const exportUrl = router.resolve({
    name: 'Export',
    query: { 
      from: 'billTotal',
      billId: row.id
    }
  }).href;
  
  console.log('生成的导出URL:', exportUrl);
  
  // 创建弹窗显示导出页面
  const modalContainer = document.createElement('div');
  modalContainer.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    z-index: 9999;
    display: flex;
    align-items: center;
    justify-content: center;
  `;
  
  modalContainer.innerHTML = `
    <div style="
      width: 90%;
      max-width: 480px;
      height: 90%;
      max-height: 800px;
      background: white;
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
      display: flex;
      flex-direction: column;
    ">
      <div style="
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 16px;
        background: #67c23a;
        color: white;
        flex-shrink: 0;
      ">
        <h3 style="margin: 0; font-size: 16px;">结算单 - ${row.billPeriod}</h3>
        <button id="modal-close-btn" style="
          background: none;
          border: none;
          color: white;
          font-size: 24px;
          cursor: pointer;
          padding: 0;
          width: 30px;
          height: 30px;
          display: flex;
          align-items: center;
          justify-content: center;
        ">×</button>
      </div>
      <div style="
        flex: 1;
        overflow: hidden;
      ">
        <iframe 
          src="${exportUrl}" 
          style="
            width: 100%;
            height: 100%;
            border: none;
          "
        ></iframe>
      </div>
    </div>
  `;
  
  // 添加到页面
  document.body.appendChild(modalContainer);
  
  // 关闭按钮事件
  const closeBtn = modalContainer.querySelector('#modal-close-btn');
  closeBtn.addEventListener('click', () => {
    document.body.removeChild(modalContainer);
  });
  
  // 点击遮罩层关闭弹窗
  modalContainer.addEventListener('click', (e) => {
    if (e.target === modalContainer) {
      document.body.removeChild(modalContainer);
    }
  });
  
  // ESC 键关闭弹窗
  const handleEsc = (e) => {
    if (e.key === 'Escape') {
      document.body.removeChild(modalContainer);
      document.removeEventListener('keydown', handleEsc);
    }
  };
  document.addEventListener('keydown', handleEsc);
};

const handleSettle = (row: any) => {
  if (!validateBillId(row)) return;
  ElMessageBox.confirm(
    `确认要重新结算该结算单数据吗？\n企业：${row.shortName}\n账期：${row.billPeriod}`,
    "重新结算",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
  .then(() => {
    let requestData = {
        idList: [row.id],
      }
    resettleBillTotal(requestData)
    .then((res: any) => {
      ElMessage.success("重新结算成功！");
      getList();
    })
    .catch((err: any) => {
      console.error("err", err.msg);
      ElMessage.error("重新结算失败！");
    });
  })
  .catch((err: any) => {
    console.error("重新结算失败:", err);
  });
};

const handleBatchSettle = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录');
    return;
  }

  ElMessageBox.confirm(
    `确认要重新结算选中的 ${selectedRows.value.length} 条结算单吗？`,
    '批量重新结算',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      let idList = selectedRows.value.map((item: any) => item.id);
      let requestData = {
        idList: idList,
      }
      resettleBillTotal(requestData)
        .then((res: any) => {
          ElMessage.success("批量重新结算成功！");
          getList();
        })
        .catch((err: any) => {
          console.error("err", err.msg);
          ElMessage.error("批量重新结算失败！");
        });
    })
    .catch((err: any) => {
      console.error("批量重新结算失败:", err);
    });
};

const handleExportAll = () => {
  exportSettleBillTotal(headerForm)
}

const enterpriseListDialogRef = ref<any>(null);
const handleNewSettle = () => {
  enterpriseListDialogRef.value.openDialog();
}

const handleCopyId = () => {
  copyValue(currentDetail.value.id, '结算单汇总ID已复制');
}

// 页面加载时获取商户列表
onMounted(() => {
  tableMaxHeight.value = window.innerHeight - 300;

  getSettlePermissions()
  .then((res: any) => {
    if (res.success) {
      settlePermissions.value = res.data;
    } else {
      console.error("获取结算操作权限失败", res.msg);
    }
  })
  .catch((err: any) => {
    console.error("err", err.msg);
  });
});

defineExpose({
  updateData,
  getList
});
</script>

<style lang="scss" scoped>
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;
  color: #909399;
  
  p {
    margin: 0;
    font-size: 14px;
    text-align: center;
    line-height: 1.5;
  }
}

// 移除表格边框
:deep(.el-table) {
  .el-table__cell {
    border-right: none !important;
  }
  
  .el-table__border-left-patch,
  .el-table__fixed-right-patch {
    display: none;
  }
}

// 详情弹窗样式
.detail-content {
  .detail-section {
    margin-bottom: 30px;
    
    h3 {
      margin: 0 0 15px 0;
      font-size: 16px;
      font-weight: 600;
      color: #303133;
      border-bottom: 2px solid #409EFF;
      padding-bottom: 8px;
    }
  }
}

:deep(.el-descriptions) {
  .el-descriptions__label {
    font-weight: 600;
    color: #606266;
  }
  
  .el-descriptions__body {
    .el-descriptions__table {
      width: 100% !important;
      table-layout: fixed !important;
      
      .el-descriptions-item__label {
        width: 200px !important;
        min-width: 200px !important;
        max-width: 200px !important;
        text-align: right !important;
        padding-right: 20px !important;
        font-weight: 600;
        color: #606266;
        background-color: #f8f9fa;
        vertical-align: middle !important;
      }
      
      .el-descriptions-item__content {
        width: 200px !important;
        min-width: 200px !important;
        max-width: 200px !important;
        padding-left: 20px !important;
        color: #303133;
        vertical-align: middle !important;
      }
    }
  }
}

.form-item-wrapper {
  margin-right: 10px;
}

.flex-wrapper {
  display: flex;
  gap: 10px;
}

.btn-dropdown {
  margin-left: 6px;
}
</style>